package com.weishenai.Filter;

import cn.hutool.json.JSONUtil;
import com.weishenai.Utils.TokenUtil;
import com.weishenai.common.Result;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @Auther: weishenai
 * @Date: 2021/10/04/17:13
 * @Description:
 */
public class myFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("myFilter init");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("myFilter exec");
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        TokenUtil tku = new TokenUtil();
        HttpServletRequest req = (HttpServletRequest) request;
        String token = (String) req.getHeader("token");
        if (token != null) {
            String username = tku.getTokenData(token).getUserName();
            if (username == null) {
                //用户名失效
                response.getWriter().print(JSONUtil.toJsonStr(Result.error("-1", "用户失效")));
            } else {
                if (tku.verify(token)) {
                    //验证成功
                    req.setAttribute("username", username);
                    chain.doFilter(request, response);
                } else {
                    //token验证失败
                    response.getWriter().print(JSONUtil.toJsonStr(Result.error("-1", "token验证失败")));
                }
            }
        } else {
            //没有登陆
            response.getWriter().print(JSONUtil.toJsonStr(Result.error("-1", "没有登陆")));
        }

    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
